import { apiRequest } from '@/utils/apiRequest'
import { ElMessage } from 'element-plus'

/**
 * 获取所有生产车间
 * @returns {Promise<{data: Array}>}
 */
export const getWorkshops = async () => {
  try {
    const response = await apiRequest.get('/api/Workshops')
    return response
  } catch (error) {
    console.error('Failed to get workshops:', error)
    ElMessage.error('获取车间列表失败: ' + error.message)
    throw error
  }
}

/**
 * 获取单个生产车间
 * @param {string|number} id - 车间ID
 * @returns {Promise<{data: Object}>}
 */
export const getWorkshop = async (id) => {
  try {
    const response = await apiRequest.get(`/api/Workshops/${id}`)
    return response
  } catch (error) {
    console.error(`Failed to get workshop ${id}:`, error)
    ElMessage.error('获取车间详情失败: ' + error.message)
    throw error
  }
}

/**
 * 创建生产车间
 * @param {Object} data - 车间数据
 * @param {string} data.name - 车间名称
 * @param {string} data.description - 车间描述
 * @param {number} data.status - 车间状态 (1: 激活, 0: 停用)
 * @returns {Promise<{data: Object}>}
 */
export const createWorkshop = async (data) => {
  try {
    const response = await apiRequest.post('/api/Workshops', data)
    ElMessage.success('创建车间成功')
    return response
  } catch (error) {
    console.error('Failed to create workshop:', error)
    ElMessage.error('创建车间失败: ' + error.message)
    throw error
  }
}

/**
 * 更新生产车间
 * @param {string|number} id - 车间ID
 * @param {Object} data - 车间数据
 * @param {string} data.name - 车间名称
 * @param {string} data.description - 车间描述
 * @param {number} data.status - 车间状态 (1: 激活, 0: 停用)
 * @returns {Promise<{data: Object}>}
 */
export const updateWorkshop = async (id, data) => {
  try {
    const response = await apiRequest.put(`/api/Workshops/${id}`, data)
    ElMessage.success('更新车间成功')
    return response
  } catch (error) {
    console.error(`Failed to update workshop ${id}:`, error)
    ElMessage.error('更新车间失败: ' + error.message)
    throw error
  }
}

/**
 * 删除生产车间
 * @param {string|number} id - 车间ID
 * @returns {Promise<void>}
 */
export const deleteWorkshop = async (id) => {
  try {
    await apiRequest.delete(`/api/Workshops/${id}`)
    ElMessage.success('删除车间成功')
  } catch (error) {
    console.error(`Failed to delete workshop ${id}:`, error)
    ElMessage.error('删除车间失败: ' + error.message)
    throw error
  }
}

/**
 * 更改生产车间状态
 * @param {string|number} id - 车间ID
 * @param {number} status - 车间状态 (1: 激活, 0: 停用)
 * @returns {Promise<{data: Object}>}
 */
export const changeWorkshopStatus = async (id, status) => {
  try {
    const response = await apiRequest.patch(`/api/Workshops/${id}/status`, status)
    ElMessage.success(`车间已${status === 1 ? '激活' : '停用'}`)
    return response
  } catch (error) {
    console.error(`Failed to change status for workshop ${id}:`, error)
    ElMessage.error('更改车间状态失败: ' + error.message)
    throw error
  }
}